export const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

// 验证纯数字或者纯字母
export function isNumberOr_Letter(str){
  var reN = '^[0-9]*$'
  var reS = '^[A-Za-z]+$'
  var ren = new RegExp(reN)
  var res = new RegExp(reS)
  if (ren.test(str) || res.test(str)) { 
    return true;
  }else{ 
    return false; 
  }
}

// 修改http:为https:
export function toHttps(val){
  if(val){
    if(val.substring(0,5) == 'http:'){
      return `https:${val.substring(5,val.length)}`
    }else{
      return val
    }
  }else{
    return val
  }
}

// 节流函数
export function throttle(func, wait, ...args){
  var pre = 0;
  return function(){
      const context = this;
      var now = Date.now();
      if (now - pre >= wait){
          func.apply(context, args);
          pre = Date.now();
      }
  }
}

// 防抖函数
export function debounceNow(func,wait,...args){
  var timeout;     //延时器变量
  return function(){
    const context = this;
    if (timeout) clearTimeout(timeout);
    var callNow = !timeout;    //是否立即执行
    timeout = setTimeout(() => {
      timeout = null;
    },wait)
    if(callNow) func.apply(context,args)
  }
}

// 防抖不立即执行函数
export function debounce(func,wait,...args) {
  var timeout;    //延时器变量
  return function () {
    const context = this;    //改变this指向
    if (timeout) clearTimeout(timeout);   //先判断有没有延时器，有则清空，毕竟要最后一次执行
    timeout = setTimeout(() => {      
      func.apply(context, args)     //apply调用传入方法
    }, wait);
  }
}